Medium
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
递归
代码的亮点在于,
- 使用递归,完美的实现了题目中需要倒置结果的需求。由于需要倒置结果(个位是linked list的头)使用以下代码,就可以在计算的同时,不断向下一位移动。
1 | ListNode ans = new ListNode(single); |
1 | /** |
syntax:
- 声明新变量时,一定要声明变量类型
- 递归调用函数时,直接调用函数名,注意函数的参数一定要与声明类型一致